import store from '@/store';
import {
  useI18n
} from "@/locales/setupI18n";
import {
	scanQrCodeToken,
	confirmQrCodeToken,
} from '@/apis/identity';

/**
 * 处理扫描
 * @param res 扫描的结果数据
 */
export async function handleScan(res) {
  const {
    t
  } = useI18n();
  // console.log('扫描结果', res);
  const tmpData = res.data.replace(/'/g, '"');
  const scanData = JSON.parse(tmpData);
  if(!scanData.Type){
  	uni.showModal({
  		title: t('scanCode.scanDataInvalid'),
  		content: `${t('scanCode.contentFormatShouldbe')} ${t('scanCode.scanDataFormat')}`,
  		showCancel: false,
  		confirmText: t('common.okText')
  	});
  	return;
  }
  // TODO：根据不同的Type处理对应的业务逻辑
  const dataType = scanData.Type.toLowerCase();
  // 扫描二维码授权PC端登录
  if(dataType === 'qrcodetoken'){
    const userInfo = store.getters.getUserInfo;
    if(userInfo.UserId){
      // 当前组织机构信息
      const organizationId = userInfo.CurrentDepartment ? userInfo.CurrentDepartment.Id : userInfo.CurrentOrganization ? userInfo.CurrentOrganization.Id : null;
      await scanQrCodeToken({
        /** 编号 */
        Id: scanData.Id,
        /** 客户端类型 */
        ClientType: scanData.ClientType,
        /** 客户端ID */
        ClientId: scanData.ClientId,
        /** 提供者秘钥 */
        ProviderKey: userInfo.UserId,
        /** 组织机构编号 */
        OrganizationId: organizationId,
      });
      const loginAccount = userInfo.NickName || userInfo.UserName || userInfo.UserId;
      uni.showModal({
      	title: t('common.warmReminderText'),
      	content: `${loginAccount}\r\n${t('common.loginConfirmText')}`,
      	success: async function(res) {
      		if (res.confirm) {
            try {
              uni.showLoading({
                  title: t('common.loadingText')
              });

              await confirmQrCodeToken({
                /** 编号 */
                Id: scanData.Id,
                /** 客户端类型 */
                ClientType: scanData.ClientType,
                /** 客户端ID */
                ClientId: scanData.ClientId,
                /** 提供者秘钥 */
                ProviderKey: userInfo.UserId,
                /** 组织机构编号 */
                OrganizationId: organizationId,
                });
            } finally {
              uni.hideLoading();
            }
      		}
      	},
      });
    }
  }

}
